package com.black.knight.chess.calls;

import org.restlet.resource.ClientResource;

import android.widget.ProgressBar;

import com.black.knight.chess.R;
import com.black.knight.chess.RegistrationActivity;
import com.black.knight.chess.common.Base;
import com.black.knight.chess.common.User;
import com.black.knight.chess.common.UserResource;
import com.black.knight.chess.model.SettingsModel;
import com.black.knight.chess.utils.Utils;

public class RegisterUserCall implements Runnable {

	private User user;
	
	private RegistrationActivity context;
	
	private Base base = null;
	
	public RegisterUserCall(User user, RegistrationActivity context) {
		this.context = context;
		this.user = user;
	}
	
	@Override
	public void run() {
		ClientResource cr = new ClientResource(SettingsModel.SERVICE_URL + "/users/" + user.getUsername());
		
		cr.setRequestEntityBuffering(true);
		
		UserResource resource = cr.wrap(UserResource.class);
		
		try {
			base = resource.register(user);
		} catch (Exception e) {
			context.runOnUiThread(new Runnable() {
				@Override
				public void run() {
					try {
						final ProgressBar progressBar = (ProgressBar) context.findViewById(R.id.progressBar);
						progressBar.setVisibility(ProgressBar.INVISIBLE);
						
						Utils.displayAlertMessage(context, context.getResources().getString(R.string.unable_to_connect_to_server));
					} catch (Exception e) { }
				}
			});
			
			return;
		}
		
		
		context.runOnUiThread(new Runnable() {
			@Override
			public void run() {
				try {
					final ProgressBar progressBar = (ProgressBar) context.findViewById(R.id.progressBar);
					progressBar.setVisibility(ProgressBar.INVISIBLE);
					
					if(base.getSuccess()) {
						Utils.displayAlertMessage(context, base.getMessage());
					} else {
						Utils.displayAlertMessage(context, base.getMessage());
					}
				} catch (Exception e) { }
			}
		});
	}
}
